<template>
  <div class="index-main">
    <!-- 通用头部 -->
    <ComHeader :config="headerConfig" @moreCall="moreBtnClick" @seachCall="seachBtnClick"></ComHeader>
    <!-- 网页内容区域 -->
    <div class="view-content have-tabbar">
        <div class="gg-img" v-if="headAdBg">
          <nuxt-link :to="headAdBg[0].target"><img :src="headAdBg[0].url" alt="广告图" width="100%"></nuxt-link>
        </div>
        <div class="haveNovel" v-if="haveNovel">
           <div class="list-wrapper" v-if="followArr.length">
                <div class="header">
                    <span class="title">特别关注</span>
                    <span class="line"></span>
                </div>
                <div class="content">
                <!-- 列表模式  -->
                <ul v-if="changeType">
                    <li class="list-type"  v-for="(item,index) in followArr" :key="index">
                        <router-link :to="{path:'/read',query:item.currentQuery}">
                            <div class="left"><img :src="item.coverimg" :alt="item.name" onerror="this.src='https://static.kuaiyankanshu.net/';this.onerror=null"></div>
                            <div class="right">
                                <p class="title ellipsis">{{item.name}}<em class="dot" v-if="item.haveUpdate"></em></p>
                                <P class="des ellipsis">{{item.lastReadName||'还未开始阅读'}}</P>
                                <p class="des ellipsis">{{common.formatMsgTime(item.lastUpdate)}} 更新 · {{item.lastChapter}}</p>
                            </div>
                        </router-link>
                        <span @click="editNovel(index,0)" class="more"></span>
                    </li>
                </ul>
                <!-- 图文模式 -->
                <ul class="imgText-type clearfix" v-if="!changeType">
                    <router-link tag="li" :to="{path:'/read',query:item.currentQuery}" v-for="(item,index) in followArr" :key="index">
                        <div class="list-item">
                            <div class="imges">
                                <img :src="item.coverimg" :alt="item.name" onerror="this.src='https://static.kuaiyankanshu.net/';this.onerror=null">
                                <span class="dot" v-if="item.haveUpdate"></span>
                            </div>
                            <p class="title ellipsis">{{item.name}}</p>
                            <P class="des ellipsis">还有{{item.SurplusChapter}}章未读</P>
                        </div>
                    </router-link>
                </ul>
                </div>
          </div>
           <!-- 最近阅读 -->
           <div class="list-wrapper" v-if="bookshelfArr.length">
                <div class="header">
                    <span class="title">最近阅读</span>
                    <span class="line"></span>
                </div>
                <div class="content">
                    <!-- 列表模式 -->
                    <ul v-if="changeType">
                        <li class="list-type" v-for="(item,index) in bookshelfArr" :key="index">
                            <router-link :to="{path:'/read',query:item.currentQuery}">
                                <div class="left"><img :src="item.coverimg" :alt="item.name" onerror="this.src='https://static.kuaiyankanshu.net/';this.onerror=null"></div>
                                <div class="right">
                                    <p class="title ellipsis">{{item.name}}<em class="dot" v-if="item.haveUpdate"></em></p>
                                    <P class="des ellipsis">{{item.lastReadName||'还未开始阅读'}}</P>
                                    <p class="des ellipsis">{{common.formatMsgTime(item.lastUpdate||item.lastupdate)}} 更新 · {{item.lastChapter}}</p>
                                </div>
                            </router-link>
                            <span @click="editNovel(index,1)" class="more"></span>
                        </li>
                    </ul>
                    <!-- 图文模式 -->
                    <ul class="imgText-type clearfix" v-if="!changeType">
                        <router-link tag="li" :to="{path:'/read',query:item.currentQuery}" v-for="(item,index) in bookshelfArr" :key="index">
                            <div class="list-item">
                                <div class="imges">
                                    <img :src="item.coverimg" :alt="item.name" onerror="this.src='https://static.kuaiyankanshu.net/';this.onerror=null">
                                    <span class="dot" v-if="item.haveUpdate"></span>
                                </div>
                                <p class="title ellipsis">{{item.name}}</p>
                                <P class="des ellipsis">还有{{item.SurplusChapter}}章未读</P>
                            </div>
                        </router-link>
                        <li>
                        <div class="list-item">
                            <div @click="$router.push('/')"><img src="~assets/image/index/addBg.png" alt="添加小说" width="100%"></div>
                            <p class="title ellipsis"></p>
                            <P class="des ellipsis"></P>
                        </div>
                        </li>
                    </ul>
                </div>
          </div>
        </div>
        <div class="noHaveNovel" v-if="!bookshelfArr.length&&!followArr.length">
          <img src="~assets/image/index/nonovel.png" alt="">
          <button @click="$router.push('/')">点我找书</button>
        </div>
    </div>
    <div class="menuPopupView" v-if="menuPopupVisible" position="top">
        <div class="overlay" @click="menuPopupVisible=false"></div>
        <div class="menu-wrapper">
           <ul>
                <li v-if="!changeType" @click="$router.push('/bookshelf/editNovel')"><i class="menuIcon setupIcon"></i>编辑书架</li>
                <li  v-if="changeType" @click="$router.push('/')"><i class="menuIcon addIcon"></i>添加小说</li>
                <li @click="sortClick"><i class="menuIcon sortIcon"></i>{{sort?'最近阅读':'时间排序'}}</li>
                <li @click="changeShowType"><i class="menuIcon" :class="showIconClass"></i>{{showTypeText}}</li>
           </ul>
        </div>
    </div>
    <mt-popup v-model="editPopupVisible" position="bottom">
        <div class="edit-wrapper">
          <button class="followBtn" @click="followClick"><i class="followIcon"></i>{{this.editType==1?'特别':'取消'}}关注</button><em>|</em><button class="deleteBtn" @click="deleteBook">删除</button>
        </div>
    </mt-popup>
    <ComFooter :selectedIndex="0"></ComFooter>
  </div>
</template>

<script>
  import {Toast,Popup ,MessageBox } from 'mint-ui'
  import api from '~/plugins/api.js'
  import axios from 'axios'
  import qs from 'qs'
  import storage from 'localforage'

//   <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
//   <meta http-equiv="pragma" content="no-cache">
//   <meta http-equiv="cache-control" content="no-cache">
//   <meta http-equiv="expires" content="0">
//   <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE9" />


  export default {
    head: {
        title: '快眼看书 - 新版快眼看书 - 小说搜索网',
        meta: [{
            name: 'description',
            content: '快眼看书小说搜索引擎聚合网络各大小说网站最新小说章节,无广告无弹窗全文阅读.'
        },{
            name: 'keyWords',
            content: '快眼看书,kuaiyankanshu,小说搜索,小说搜索网'
        } ,
        { 'http-equiv': 'pragma', content: 'no-cache' },
        { 'http-equiv': 'cache-control', content: 'no-cache' },
        { 'http-equiv': 'expires', content: '0' }]
    },
    data () {
      return {
        headerConfig: {
          showBackButton: false, // 头部返回上一页按钮
          showCompleteBtn: true,// 确定按钮是否显示
          title: '书架'
        },
        userInfo: {},
        msg: 0,
        changeType: true,
        menuPopupVisible: false,
        showIconClass: 'showImgTextIcon',
        showTypeText: '图文模式',
        editPopupVisible: false,
        haveNovel: true,
        headAdBg: '',
        sort: false,
        bookshelfArr: [],
        followArr: [],
        editIndex: 0,
        editType: 0,
        timestampArr: []
      }
    },
    created(){
        if(!process.server){
            this.initData()
            this.getAdData()
        }
    },
    mounted(){
    },
    methods: {
        /**
         * 显示更多菜单
         */
        moreBtnClick() {    
            this.menuPopupVisible = true
        },
        /**
         * 跳转搜索页
         */
        seachBtnClick() {
            this.$router.push('/bookshelf/search')
        },
        /**
         * 列表/图文模式切换
         */
        changeShowType() {
            this.changeType = !this.changeType
            this.showIconClass = this.changeType==true?"showImgTextIcon":"showListIcon"
            this.showTypeText = this.changeType==true?"图文模式":"列表模式"
            this.menuPopupVisible = false
            storage.setItem('saveChangeType',this.changeType)
        },
        /**
         * 列表模式下编辑
         */
        editNovel(i,type) {
            this.editPopupVisible = true
            this.editIndex = i
            this.editType = type
        },
        /**
         * 特别关注
         */
        followClick () {
            if(this.editType==1){
                this.followArr.unshift(this.bookshelfArr[this.editIndex])
                this.bookshelfArr.splice(this.editIndex,1)
            }else{
                this.bookshelfArr.unshift(this.followArr[this.editIndex])
                this.followArr.splice(this.editIndex,1)
            }
            storage.setItem('followKey',this.followArr)
            this.editPopupVisible = false
        },
        /**
         *  从书架删除小说
         */
        async deleteBook() {
            this.editPopupVisible = false
            MessageBox.confirm('您确定删除这本书籍吗?').then(action => {
                this.deleteBookAction()
            }).catch(resp => {}); 
        },
        async deleteBookAction() {
            let novel_id = ''
            if(this.editType==1){
                novel_id = this.bookshelfArr[this.editIndex].novelid
            }else{
                novel_id = this.followArr[this.editIndex].novelid
            }
            let paramsData = {}
            if(this.userInfo){
                paramsData = {
                    novel_id: novel_id,
                    token: this.userInfo.token,
                    uid: this.userInfo.uid
                }
                let result = await axios.post(api.deleteNovel,qs.stringify(paramsData))
                if(result){
                    //Toast(result.data.info)
                    let tStr = `  书籍删除已成功 ,数据将在十分钟后同步`
                    Toast(tStr)
                }
            }
            if(this.editType==1){
                this.bookshelfArr.splice(this.editIndex,1)
                storage.setItem('bookshelfKey',this.bookshelfArr)
            }else{
                this.followArr.splice(this.editIndex,1)
                storage.setItem('followKey',this.followArr)
            }
            let bookshelfIdArr = await storage.getItem('bookshelfIdKey')
            bookshelfIdArr.remove(parseInt(novel_id))
            await storage.setItem('bookshelfIdKey',bookshelfIdArr)
            this.initData()
        },
        /**
         * 时间排序/最近阅读切换
         */
        sortClick() {
            this.sort=!this.sort
            this.menuPopupVisible = false
            this.initData()
        },
        async initData() {
            this.followArr = await storage.getItem('followKey') || []
            this.changeType = await storage.getItem('saveChangeType')
            this.userInfo = await storage.getItem('userinfo')
            if(this.userInfo){
                this.getmyBookshelf()
            }else{
                this.getUnLogin()
            }
        },
        /**
         * 获取广告
         */
        async getAdData() {
            let result = await axios.get(api.shelf)
            if(result){
                this.headAdBg = result.data.data[0]
            }
        },
        /**
         * 获取未登录书架
         */
        async getUnLogin() {
            let arr = await storage.getItem('bookshelfIdKey') || []
            let ids = ''
            if(arr.length){
                ids = arr.join()
            }
            let result = await axios.get(api.unLogin,{params:{novelId:ids}})
            if(result){
                this.bookshelfArr = this.common.unique(result.data.data,this.followArr,'novelId')
                storage.setItem('bookshelfKey',this.bookshelfArr)
                this.bookshelfArr = await this.lastUpdateAction(this.bookshelfArr)
                this.followArr = await this.lastUpdateAction(this.followArr)
            }
        },
        /**
         * 获取个人书架
         */
        async getmyBookshelf() {
            let paramsData = {
                uid: this.userInfo.uid,
                sort: this.sort,
                token: this.userInfo.token
            }
            let result = await axios.get(api.myBookshelf,{
                // headers: {
                //     'cache': false
                // },
                params: paramsData
            })
            if(result){
              let arr = result.data.data
              let idarr = arr.map(function(item){
                  return item.novelid
              })
              storage.setItem('bookshelfIdKey',idarr)
              this.bookshelfArr = this.common.unique(arr,this.followArr,'novelId')
              storage.setItem('bookshelfKey',this.bookshelfArr)
              this.bookshelfArr = await this.lastUpdateAction(this.bookshelfArr)
              this.followArr = await this.lastUpdateAction(this.followArr)
            }
        },
        /**
         * 获取上次阅读的章节信息
         */
        async lastUpdateAction(arr) {
            let obj = await storage.getItem('timestampKey') || {}
            let newArr = arr.map(function(item,index){
                let itemObj = obj[item.novelId]
                if(itemObj){
                    if(item.lastUpdate>itemObj.timestamp){
                        item['haveUpdate'] = true
                    }
                    item['currentQuery'] = itemObj.currentQuery
                    item['lastReadName'] = '上次读至 - '+itemObj.lastChapter
                    item['readTimestamp'] = itemObj.timestamp
                    let noread = parseInt(item.lastChapterId) - parseInt(itemObj.currentQuery.chapterId)
                    item['SurplusChapter'] = noread==0? '1':noread
                }else{
                    item['currentQuery'] = {
                        novelId: item.novelId,
                        chapterId: '1',
                        siteId: item.siteId
                    }
                    item['readTimestamp'] = item.lastUpdate
                    item['SurplusChapter'] = parseInt(item.lastChapterId)
                }
                return item
            })
            if(!this.sort){  // 最近阅读排序
                newArr.sort(this.common.compare("readTimestamp"))
            }
            return newArr
        }
       
        
    }
  }
</script>
